import { resolve } from "dns";
import { reject } from "q";

function pluralize(time, label) {
  if (time === 1) {
    return time + label
  }
  return time + label + 's'
}

export function arrFindToObj(arrKey,backKey,value,arr){   // 由键值查找在数组中对应的对象
  // console.log(arr.find(item => item[arrKey] === value)[backKey],"由键值查找在数组中对应的对象");
  
  return arr.find(item => item[arrKey] === value)?arr.find(item => item[arrKey] === value)[backKey]:`${value}检索失败`
}


// export function arrayUnique2(arr, name){     //过滤数组对象中指定重复键值的对象
//   // this.linksData = this.arrayUnique2(aaa,"name")
//   var hash = {}
//   return arr.reduce(function (item, next) {
//     hash[next[name]] ? '' : hash[next[name]] = true && item.push(next)
//     return item
//   }, [])
//   // return hash
// }
export function blobToBase64(blob) {
  let bytes = new Uint8Array(blob);
  let data = "";
  let len = bytes.byteLength;
  for (let i = 0; i < len; i++) {
  　　data += String.fromCharCode(bytes[i]);
  }
  // return "" + window.btoa(data);
  return "data:image/jpeg;base64," + window.btoa(data) + "jpeg";
}


export function urlImgToBlob(url){   //
    let imgBlob
    function preView(url){
      return new Promise((resolve) => {
        var reader = new FileReader();
        function getImageBlob(url, cb) {
          var xhr = new XMLHttpRequest();
          xhr.open("get", url, true);
          xhr.responseType = "";
          xhr.onload = function() {
            if (this.status == 200) {
              if(cb) cb(this.response);
            }
          };
          xhr.send();
          console.log('=====-------++++++=')
          console.log(xhr)
        }
        getImageBlob( url , function(blob){
          reader.readAsDataURL(blob);
        });
        reader.onload = function(e) {
          resolve( e.target.result )
        }
      })
      // console.log('7777777777777',imgData);
      
    }
    imgBlob = preView().then((res) => {
      return res
    })
    console.log('00000000000000000022222222222222000000000000000',imgBlob)

  return imgBlob
}

export function timesago(dateTimeStamp){   //dateTimeStamp是一个时间毫秒，注意时间戳是秒的形式，在这个毫秒的基础上除以1000，就是十位数的时间戳。13位数的都是时间毫秒。
  var minute = 1000 * 60;      //把分，时，天，周，半个月，一个月用毫秒表示
  var hour = minute * 60;
  var day = hour * 24;
  var week = day * 7;
  var month = day * 30;
  var now = new Date().getTime();   //获取当前时间毫秒
  var result;
  var diffValue = now - dateTimeStamp;//时间差

  if(diffValue < 0){
      return;
  }
  var minC = diffValue/minute;  //计算时间差的分，时，天，周，月
  var hourC = diffValue/hour;
  var dayC = diffValue/day;
  var weekC = diffValue/week;
  var monthC = diffValue/month;
  if(monthC >= 1 && monthC <= 3){
      result = " " + parseInt(monthC) + "月前"
  }else if(weekC >= 1 && weekC <= 3){
      result = " " + parseInt(weekC) + "周前"
  }else if(dayC >= 1 && dayC <= 6){
      result = " " + parseInt(dayC) + "天前"
  }else if(hourC >= 1 && hourC <= 23){
      result = " " + parseInt(hourC) + "小时前"
  }else if(minC >= 1 && minC <= 59){
      result =" " + parseInt(minC) + "分钟前"
  }else if(diffValue >= 0 && diffValue <= minute){
      result = "刚刚"
  }else {
      var datetime = new Date();
      datetime.setTime(dateTimeStamp);
      var Nyear = datetime.getFullYear();
      var Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
      var Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
      // var Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
      // var Nminute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
      // var Nsecond = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
      result = Nyear + "-" + Nmonth + "-" + Ndate
  }
  return result;
}
export function timeAgo(time) {
  const between = Date.now() / 1000 - Number(time)
  if (between < 3600) {
    return pluralize(~~(between / 60), ' minute')
  } else if (between < 86400) {
    return pluralize(~~(between / 3600), ' hour')
  } else {
    return pluralize(~~(between / 86400), ' day')
  }
}
export function timeago(time){
  const d = new Date(+time)
  return (d.getFullYear() + '-' + (d.getMonth() +1 ).toString().padStart(2,'0') + '-' + (d.getDate() +1 ).toString().padStart(2,'0'))
}
export function formatSize(value) {
  if (null === value || value === "") {
    return "0B"
  }
  let unitArr = new Array("B", "KB", "MB", "GB", "TB")
  let index = 0
  let srcsize = parseFloat(value)
  index = Math.floor(Math.log(srcsize) / Math.log(1024))
  let size = srcsize / Math.pow(1024, index)
  if (index > 0) {
    size = size.toFixed(2)
  }
  return size + unitArr[index]
}

export function formatNumber(num, precision, separator) {
  let parts
  if (!isNaN(parseFloat(num)) && isFinite(num)) {
    // 把类似 .5, 5. 之类的数据转化成0.5, 5, 为数据精度处理做准备, 至于为什么
    // 不在判断中直接写 if (!isNaN(num = parseFloat(num)) && isFinite(num))
    // 是因为parseFloat有一个奇怪的精度问题, 比如 parseFloat(12312312.1234567119)
    // 的值变成了 12312312.123456713
    num = Number(num)
    // Process decimal digits
    num = (typeof precision !== "undefined" ? num.toFixed(precision) : num).toString()
    // separate the decimal part and integral part of a number
    parts = num.split(".")
    // add [separator] to integral part, use a known regx
    parts[0] = parts[0].toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1" + (separator || ","))
    return parts.join(".")
  }
  return NaN
}

export function id2name(id,arr){
  arr.map(res => {
    if(res.id === id){
      return res
    }
  })
}

export function uppercaseFirst(string) {
  return string.charAt(0).toUpperCase() + string.slice(1)
}

// timestamp
const padding = (s, len) => {
  const _len = len - (`${s}`).length
  for (let i = 0; i < _len; i++) {
    s = `0${s}`
  }
  return s
}
const formatDatetime = (date, pattern = 'yyyy-MM-dd') => {
  return pattern.replace(/([yMdhsm])(\1*)/g, ($0) => {
    switch ($0.charAt(0)) {
    case 'y': return padding(date.getFullYear(), $0.length)
    case 'M': return padding(date.getMonth() + 1, $0.length)
    case 'd': return padding(date.getDate(), $0.length)
    case 'w': return date.getDay() + 1
    case 'h': return padding(date.getHours(), $0.length)
    case 'm': return padding(date.getMinutes(), $0.length)
    case 's': return padding(date.getSeconds(), $0.length)
    }
  })
}
export const formatStamp = (timestamp) => {
  if (!timestamp) {
    return '--'
  }
  const date = new Date(timestamp)
  return formatDatetime(date, 'yyyy-MM-dd')
  // return formatDatetime(date, 'yyyy-MM-dd hh:mm:ss')
}
